//导入websocket模块：
const WebSocket = require('ws');

//引用Server类：
const WebSocketServer = WebSocket.Server;

//实例化
const wss = new WebSocketServer({
    port: 3000
});
console.log('ws:listen');

//广播  
wss.broadcast = function broadcast(s,ws) {  
    // console.log(ws);  
    // debugger;  
    wss.clients.forEach(function each(client) {
        // if (typeof client.user != "undefined") {  
            if(s == 1){  
                client.send(ws.name + ":" + ws.msg);
            }  
            if(s == 0){  
                client.send(ws + "退出聊天室");    
            }  
        // }  
    });  
};  

// 初始化  
wss.on('connection', function(ws) {  
    console.log("在线人数", wss.clients.length);  
    ws.send('你是第' + wss.clients.length + '位');  
    // 发送消息
    ws.on('message', function(jsonStr) {
        this.msg = jsonStr;
        console.log(`收到消息，${jsonStr}`);
        if (typeof this.msg != "undefined") {
            wss.broadcast(1,this);  
        }
    });
    // 退出聊天  
    ws.on('close', function(close) {  
        try{  
            wss.broadcast(0, this);  
        }catch(e){  
            console.log('刷新页面了');  
        }  
    });  
});